package com.jim.healio.controller;

import com.jim.healio.graphrag.model.MedicalEntity;
import com.jim.healio.graphrag.model.DocumentSearchResult;
import com.jim.healio.graphrag.service.GraphRAGService;
import com.jim.healio.graphrag.service.impl.RealGraphRAGServiceImpl;
import com.jim.healio.graphrag.service.EntityValidationService;
import com.jim.healio.tools.GraphRAGTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * GraphRAG测试控制器
 * 用于测试GraphRAG功能的REST API
 */
@RestController
@RequestMapping("/graphrag/test")
public class GraphRAGTestController {
    
    private static final Logger logger = LoggerFactory.getLogger(GraphRAGTestController.class);
    
    @Autowired
    private GraphRAGService graphRAGService;
    
    @Autowired
    private GraphRAGTool graphRAGTool;
    
    @Autowired(required = false)
    private RealGraphRAGServiceImpl realGraphRAGService;
    
    @Autowired
    private EntityValidationService entityValidationService;
    
    /**
     * 测试查询医学实体
     */
    @GetMapping("/entities")
    public Map<String, Object> testQueryEntities(@RequestParam String query) {
        logger.info("测试查询医学实体: {}", query);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<MedicalEntity> entities = graphRAGService.queryEntities(query);
            result.put("success", true);
            result.put("query", query);
            result.put("entities", entities);
            result.put("count", entities.size());
            
        } catch (Exception e) {
            logger.error("查询医学实体失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试文档语义搜索
     */
    @GetMapping("/documents")
    public Map<String, Object> testSemanticSearch(
        @RequestParam String query,
        @RequestParam(defaultValue = "5") int limit
    ) {
        logger.info("测试文档语义搜索: {}, 限制: {}", query, limit);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DocumentSearchResult> documents = graphRAGService.semanticSearch(query, limit);
            result.put("success", true);
            result.put("query", query);
            result.put("documents", documents);
            result.put("count", documents.size());
            
        } catch (Exception e) {
            logger.error("文档语义搜索失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试症状关联分析
     */
    @GetMapping("/symptoms")
    public Map<String, Object> testSymptomAnalysis(@RequestParam String symptoms) {
        logger.info("测试症状关联分析: {}", symptoms);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<MedicalEntity> relatedEntities = graphRAGService.analyzeSymptomRelations(
                List.of(symptoms.split(","))
            );
            result.put("success", true);
            result.put("symptoms", symptoms);
            result.put("related_entities", relatedEntities);
            result.put("count", relatedEntities.size());
            
        } catch (Exception e) {
            logger.error("症状关联分析失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试药物相互作用查询
     */
    @GetMapping("/drug-interactions")
    public Map<String, Object> testDrugInteractions(@RequestParam String drugs) {
        logger.info("测试药物相互作用查询: {}", drugs);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<MedicalEntity> interactions = graphRAGService.queryDrugInteractions(
                List.of(drugs.split(","))
            );
            result.put("success", true);
            result.put("drugs", drugs);
            result.put("interactions", interactions);
            result.put("count", interactions.size());
            
        } catch (Exception e) {
            logger.error("药物相互作用查询失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试GraphRAG工具（模拟Bob的调用）
     */
    @PostMapping("/tool/medical-knowledge")
    public Map<String, Object> testMedicalKnowledgeTool(
        @RequestParam String query,
        @RequestParam(defaultValue = "true") boolean includeDocuments
    ) {
        logger.info("测试GraphRAG医学知识工具: {}, 包含文档: {}", query, includeDocuments);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String toolResult = graphRAGTool.queryMedicalKnowledge(query, includeDocuments);
            result.put("success", true);
            result.put("query", query);
            result.put("include_documents", includeDocuments);
            result.put("tool_result", toolResult);
            
        } catch (Exception e) {
            logger.error("GraphRAG医学知识工具测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试症状关联工具
     */
    @PostMapping("/tool/symptom-relations")
    public Map<String, Object> testSymptomRelationsTool(@RequestParam String symptoms) {
        logger.info("测试症状关联工具: {}", symptoms);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String toolResult = graphRAGTool.analyzeSymptomRelations(symptoms);
            result.put("success", true);
            result.put("symptoms", symptoms);
            result.put("tool_result", toolResult);
            
        } catch (Exception e) {
            logger.error("症状关联工具测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试药物相互作用工具
     */
    @PostMapping("/tool/drug-interactions")
    public Map<String, Object> testDrugInteractionsTool(@RequestParam String drugs) {
        logger.info("测试药物相互作用工具: {}", drugs);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String toolResult = graphRAGTool.queryDrugInteractions(drugs);
            result.put("success", true);
            result.put("drugs", drugs);
            result.put("tool_result", toolResult);
            
        } catch (Exception e) {
            logger.error("药物相互作用工具测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试治疗指南工具
     */
    @PostMapping("/tool/treatment-guidelines")
    public Map<String, Object> testTreatmentGuidelinesTool(@RequestParam String condition) {
        logger.info("测试治疗指南工具: {}", condition);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String toolResult = graphRAGTool.getTreatmentGuidelines(condition);
            result.put("success", true);
            result.put("condition", condition);
            result.put("tool_result", toolResult);
            
        } catch (Exception e) {
            logger.error("治疗指南工具测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试实体验证工具
     */
    @PostMapping("/tool/validate-entities")
    public Map<String, Object> testEntityValidation(@RequestParam String entities) {
        logger.info("测试实体验证工具: {}", entities);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String toolResult = graphRAGTool.validateAndSuggestEntities(entities);
            result.put("success", true);
            result.put("entities", entities);
            result.put("tool_result", toolResult);
            
        } catch (Exception e) {
            logger.error("实体验证工具测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试实体解析
     */
    @GetMapping("/entity/resolve")
    public Map<String, Object> testEntityResolution(@RequestParam String entity) {
        logger.info("测试实体解析: {}", entity);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            EntityValidationService.EntityResolutionResult resolution = 
                entityValidationService.resolveEntity(entity);
                
            result.put("success", true);
            result.put("entity", entity);
            result.put("resolved", resolution.isResolved());
            result.put("entity_id", resolution.getEntityId());
            result.put("entity_name", resolution.getEntityName());
            result.put("confidence", resolution.getConfidence());
            result.put("reason", resolution.getReason());
            result.put("suggestions", resolution.getSuggestions());
            
        } catch (Exception e) {
            logger.error("实体解析测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取实体建议
     */
    @GetMapping("/entity/suggestions")
    public Map<String, Object> testEntitySuggestions(
        @RequestParam String entity,
        @RequestParam(defaultValue = "5") int limit
    ) {
        logger.info("测试实体建议: {}, 限制: {}", entity, limit);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<EntityValidationService.EntitySuggestion> suggestions = 
                entityValidationService.findSimilarEntities(entity, limit);
                
            result.put("success", true);
            result.put("entity", entity);
            result.put("suggestions", suggestions);
            result.put("count", suggestions.size());
            
        } catch (Exception e) {
            logger.error("实体建议测试失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取系统状态
     */
    @GetMapping("/status")
    public Map<String, Object> getSystemStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 测试基本查询功能
            List<MedicalEntity> testEntities = graphRAGService.queryEntities("糖尿病");
            List<DocumentSearchResult> testDocuments = graphRAGService.semanticSearch("高血压", 2);
            
            status.put("graphrag_service", "正常");
            status.put("entity_count", testEntities.size());
            status.put("document_count", testDocuments.size());
            status.put("tools_available", true);
            status.put("timestamp", System.currentTimeMillis());
            
            // 添加详细系统状态
            if (realGraphRAGService != null) {
                status.put("system_details", realGraphRAGService.getSystemStatus());
            }
            
        } catch (Exception e) {
            logger.error("系统状态检查失败", e);
            status.put("graphrag_service", "异常");
            status.put("error", e.getMessage());
        }
        
        return status;
    }
} 